use std::path::PathBuf;

use anyhow::Result;
use structopt::StructOpt;

use cmd::Application;


mod cmd;
mod data;
mod full;
mod miner;
mod rpc;


fn init_log(file: Option<PathBuf>) -> Result<()> {
    let log =  fern::Dispatch::new()
        .format(|out, message, record| {
            out.finish(format_args!(
                "{}[{}][{}] {}",
                chrono::Local::now().format("[%Y-%m-%d %H:%M:%S]"),
                record.target(),
                record.level(),
                message
            ))
        })
        .level(log::LevelFilter::Debug);
    match file {
        Some(f) => {
            let p = f.join("pledge.log");
            log.chain(fern::log_file(p)?).apply()?;
        },
        None => {
            log.chain(std::io::stdout()).apply()?;
        }
    }
    Ok(())
}

#[tokio::main]
async fn main() {
    dotenv::dotenv().ok();
    let app = Application::from_args();
    log::info!("{:#?}", app);

    let _ = init_log(app.log.clone());

    let r = app.run().await;
    match r {
        Ok(o) => if let Some(i) = o {
            log::info!("{}", i.show())
        },
        Err(e) => log::info!("error: {:#?}", e),
    }
}